<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Transaction
{
    /**
     * 全局数据库事务中间件
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, Closure $next)
    {

        DB::beginTransaction();

        $response = $next($request);

        if ($response->status() < 500) {

            DB::commit();
        } else {
            DB::rollBack();
        }

        return $response;
    }
}
